package controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import orm.Users;
import services.UsersBiz;

@Controller
public class UsersAction {
	@Autowired
	UsersBiz usersBiz;

	// 帐号是否存在
	@RequestMapping(value = "checkUserno")
	public void test1(String userno, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		if (usersBiz.checkUserno(userno) == 0) {
			System.out.println("可以注册!");
			out.print("<span style='color:green;'>可以注册!</span>");
		} else {
			System.out.println("已经注册!");
			out.print("<span style='color:red;'>已经注册!</span>");
		}
	}

	// 注册用户
	// 如果自动封装到Users实体类中,是获得不到值的
	@RequestMapping("register")
	public String test2(MultipartHttpServletRequest request) {
		System.out.println("昵称:" + request.getParameter("user_name"));
		MultipartFile file = request.getFile("user_img");
		String fileName = file.getOriginalFilename();
		try {
			InputStream in = file.getInputStream();
			String path = request.getSession().getServletContext().getRealPath(
					"/images/user");
			File newFile = new File(path, fileName);
			FileOutputStream fos = new FileOutputStream(newFile);
			IOUtils.copy(in, fos);
			fos.close();
			in.close();
			System.out.println("上传图片[" + fileName + "]成功!");

			// 注册开始
			Users user = new Users();
			user.setRol_id(3);
			user.setUser_no(request.getParameter("user_no"));
			user.setUser_name(request.getParameter("user_name"));
			user.setUser_logpwd(request.getParameter("user_logpwd"));
			user.setUser_img("images/user/" + fileName);// 照片:项目的相对路径

			usersBiz.register(user);

			return "index.jsp";
		} catch (IOException e) {
			e.printStackTrace();
			return "register.jsp";
		}
	}

	// 登录
	@RequestMapping("login")
	public String test3(String userNo, String password,HttpSession session) {
		// 验证  user
		Users user = usersBiz.login(userNo, password);
		if(user!=null){
			//登录成功的对象,放在session中
			session.setAttribute("user", user);
			return "init.jsp";
		}else
			return "login.jsp?fail=登录失败,帐号密码不匹配";
	}
}




